#! /usr/bin/python
from scapy.all import *
from collections import Counter

from math import log
import sys

ipssrc = {}
ipsdst = {}


def entropia(ips):
    N = sum(ips.values())
    Ps = [k/N for k in ips.values()]
    H = -sum([p*log(p,2) for p in Ps])
    return H


def arp_monitor_callback(pkt):
    if ARP in pkt and pkt[ARP].op in (1, 2):  # who-has or is-at
        src = pkt[ARP].psrc
        dst = pkt[ARP].pdst

        if not src in ipssrc: ipssrc[src] = 0.0
        ipssrc[src]+= 1
        if not dst in ipsdst: ipsdst[dst] = 0.0
        ipsdst[dst]+= 1

        return "H_src=%f, H_dst=%f" % (entropia(ipsdst), entropia(ipssrc))


def entropia_por_ip():
    ips_todas = set()

    ips_todas.update(ipssrc.keys(), ipsdst.keys())
    ips_counter = Counter({ip: (ipssrc.get(ip, 0) + ipsdst.get(ip, 0)) for ip in ips_todas})

    for ip in ips_counter:
        print "IP: %s, P(0): %s P(1): %s" % (ip, ipssrc.get(ip, 0)/ips_counter[ip], ipsdst.get(ip, 0)/ips_counter[ip])


if len(sys.argv) < 2:
    print "Usage: entropia.py [dump_file]"
    sys.exit(1)

output=sys.argv[1]
result = sniff(prn=arp_monitor_callback, filter="arp")

entropia_por_ip()

resultCount = len(result)
if resultCount > 0:
    scapy.all.wrpcap(output, result)

#show result summary
print "Paquetes capturados:", resultCount
